/*
 * Copyright (c) 2009 Frederic Daoud
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.stripesbook.rayures.util;

/**
 * A simple class to represent a location returned by a
 * {@link org.stripesbook.rayures.service.LookupStrategy}.
 *
 * @author Frederic Daoud
 */
public class Location {
  private String pkg;
  private String className;

  public Location(String fullClassName) {
    int index = fullClassName.lastIndexOf('.');
    this.pkg = fullClassName.substring(0, index);
    this.className = fullClassName.substring(index + 1);
  }

  public Location(String pkg, String className) {
    this.pkg = pkg;
    this.className = className;
  }

  public String getClassPath() {
    if (className.length() > 0) {
      return pkg + "." + className;
    }
    return pkg;
  }

  public String getClassPath(String fileInDirectory, String fileSuffix) {
    return getPath(fileInDirectory, fileSuffix, ".");
  }

  public String getFilePath(String fileInDirectory, String fileSuffix) {
    return "/" + getPath(fileInDirectory, fileSuffix, "/");
  }

  private String getPath(String fileInDirectory, String fileSuffix, String separator) {
    String classPath = getClassPath().replaceAll("\\.", separator);

    if (className.length() == 0) {
      classPath += separator + fileInDirectory;
    }
    else {
      classPath += fileSuffix;
    }
    return classPath;
  }

  public String getPathAndFile() {
    return pkg + className;
  }

  @Override
  public boolean equals(Object obj) {
    if (obj instanceof Location) {
      Location other = (Location) obj;
      return pkg.equals(other.pkg) && className.equals(other.className);
    }
    return false;
  }

  @Override
  public int hashCode() {
    return getClassPath().hashCode();
  }

  @Override
  public String toString() {
    return String.format("Location[pkg=%s, className=%s]", pkg, className);
  }
}
